//
//  GDYTranslateTool.m
//  iphoneLive
//
//  Created by YB007 on 2022/4/8.
//  Copyright © 2022 cat. All rights reserved.
//

#import "GDYTranslateTool.h"

@implementation GDYTranslateTool
// 接口语言标识
+(NSString *)serviceLang;{
    if ([lagType isEqual:ZH_CN]) {
        return @"zh-cn";
    }
    return @"en";
}
/// 是否包含中文
+(BOOL)isChinese:(NSString *)str{
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4E00 && a < 0x9FFF){
            return YES;
        }
    }
    return NO;
}
/// 纯数字
+(BOOL)isPureNumandCharacters:(NSString *)string{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0) {
        return NO;
    }
    return YES;
}
/// 是否包含英文字符
+(BOOL)isContainedEn:(NSString *)str {
    NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSInteger count = [numberRegular numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    //count是str中包含[A-Za-z]数字的个数，只要count>0，说明str中包含数字
    if (count > 0) {
        return YES;
    }
    return NO;
}
/// 纯标点
-(BOOL)isAllCharacterString:(NSString *)string{
    NSString *regex = @"[~`!@#$%^&*()_+-=[]|{};':\",./<>?]{,}/";//规定的特殊字符，可以自己随意添加
    //计算字符串长度
    NSInteger str_length = [string length];
    NSInteger allIndex = 0;
    for (int i = 0; i<str_length; i++) {
        //取出i
        NSString *subStr = [string substringWithRange:NSMakeRange(i, 1)];
        if([regex rangeOfString:subStr].location != NSNotFound){  //存在
            allIndex++;
        }
    }
    if (str_length == allIndex) {
        //纯特殊字符
        return YES;
    }else {
        //非纯特殊字符
        return NO;
    }
}

// 是否展示翻译按钮
+(BOOL)judgeShowTranslateBtn:(NSString *)originStr; {
    
    return NO;
    
    originStr = [self delEmojiWithOriginStr:originStr];
    
    /// 空字符-不显示
    NSString *delStr = [originStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (delStr.length<=0 || [PublicObj checkNull:delStr]) {
        return NO;
    }
    /// 纯数字-不显示
    if ([self isPureNumandCharacters:originStr]) {
        return NO;
    }
    BOOL isChi = [self isChinese:originStr];
    BOOL isEn = [self isContainedEn:originStr];
    if ([lagType isEqual:EN]) {
        return isChi;
    }else{
        return isEn;
    }
}

+(void)requestTranslateToken {
    
    NSString *baseUrl = @"https://aip.baidubce.com/oauth/2.0/token";
    NSDictionary *pullDic = @{
        @"grant_type":@"client_credentials",
        @"client_id":TransApiKey,
        @"client_secret":TransSecret,
    };
    //baseUrl = [baseUrl stringByAppendingFormat:@"%@",[self dealWithParam:pullDic]];
    baseUrl = [baseUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseUrl]];
    [request setHTTPMethod:@"POST"];
   
    //把字典中的参数进行拼接
    NSString *body = [self dealWithParam:pullDic];
    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
    //设置请求体
    [request setHTTPBody:bodyData];
    //设置本次请求的数据请求格式
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    // 设置本次请求请求体的长度(因为服务器会根据你这个设定的长度去解析你的请求体中的参数内容)
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)bodyData.length] forHTTPHeaderField:@"Content-Length"];

    //设置请求最长时间
    request.timeoutInterval = 15;
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            //利用iOS自带原生JSON解析data数据 保存为Dictionary
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"=======dic:%@",dict);
            if ([dict valueForKey:@"access_token"]) {
                [GDYTranslateTool saveAccesToken:[dict valueForKey:@"access_token"]];
            }else{
                [GDYTranslateTool saveAccesToken:@""];
            }
        }else{
            [GDYTranslateTool saveAccesToken:@""];
        }
    }];
    [task resume];
}

// 翻译
+(void)requestTranslateWithStr:(NSString *)originStr complete:(TranslateBlock)translate;{
    
    
    originStr = [self delEmojiWithOriginStr:originStr];
    
    
    NSString *accessToken = [self getAccesToken];
    NSString *gdy_from = @"zh";
    NSString *gdy_to = @"en";
    if ([lagType isEqual:ZH_CN]) {
        gdy_from = @"en";
        gdy_to = @"zh";
    }
    
    NSString *baseUrl = [NSString stringWithFormat:@"https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=%@",accessToken];
    NSDictionary *pullDic = @{
        @"from":gdy_from,
        @"to":gdy_to,
        @"q":originStr,
    };
    //baseUrl = [baseUrl stringByAppendingFormat:@"%@",[self dealWithParam:pullDic]];
    baseUrl = [baseUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseUrl]];
    [request setHTTPMethod:@"POST"];

    //把字典中的参数进行拼接
    /*
    NSString *body = [self dealWithParam:pullDic];
    NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
    */
    NSData* bodyData =[NSJSONSerialization dataWithJSONObject:pullDic options:NSJSONWritingPrettyPrinted error:nil];
    //设置请求体
    [request setHTTPBody:bodyData];
    //设置本次请求的数据请求格式
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    // 设置本次请求请求体的长度(因为服务器会根据你这个设定的长度去解析你的请求体中的参数内容)
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)bodyData.length] forHTTPHeaderField:@"Content-Length"];

    //设置请求最长时间
    request.timeoutInterval = 15;
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            //利用iOS自带原生JSON解析data数据 保存为Dictionary
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"fy=======dic:%@",dict);
            if ([dict valueForKey:@"error_msg"]) {
                NSString *eStr = [NSString stringWithFormat:@"%@-%@",[dict valueForKey:@"error_code"],[dict valueForKey:@"error_msg"]];
                if (translate) {
                    translate(NO,eStr);
                }
            }else{
                NSDictionary *rstDic = [dict valueForKey:@"result"];
                NSDictionary *transDic = [[rstDic valueForKey:@"trans_result"] firstObject];
                NSString *transRs = minstr([transDic valueForKey:@"dst"]);
                if (translate) {
                    translate(YES,transRs);
                }
            }
        }else{
            if (translate) {
                translate(NO,@"translate internal error");
            }
        }
    }];
    [task resume];
}

#pragma mark -- 拼接参数
+(NSString *)dealWithParam:(NSDictionary *)param {
    NSArray *allkeys = [param allKeys];
    NSMutableString *result = [NSMutableString string];
    
    for (NSString *key in allkeys) {
        NSString *string = [NSString stringWithFormat:@"%@=%@&", key, param[key]];
        [result appendString:string];
    }
    NSString *newStr = [result substringToIndex:(result.length-1)];
    return newStr;
}

+(void)saveAccesToken:(NSString *)save{
    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
    [userDef setObject:save forKey:@"gdy_bd_access_token"];
    [userDef synchronize];
}
+(NSString *)getAccesToken{
    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
    NSString *getVal = [userDef objectForKey:@"gdy_bd_access_token"];
    return getVal;
}


#pragma mark - 将表情踢出

+(NSString *)delEmojiWithOriginStr:(NSString *)originStr{
    //匹配表情文字
    NSArray *resultArr  = [PublicObj machesWithPattern:emojiPattern andStr:originStr];
    if (!resultArr){
        return originStr;
    }
    
    NSUInteger lengthDetail = 0;
    NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc]initWithString:originStr];
    //NSLog(@"del ======>\n%@",attstr);
    //遍历所有的result 取出range
    for (NSTextCheckingResult *result in resultArr) {
        //取出图片名
        NSString *imageName = [originStr substringWithRange:NSMakeRange(result.range.location, result.range.length)];
        //NSLog(@"--------%@",imageName);
        /*
        NSTextAttachment *attach = [[NSTextAttachment alloc] init];
        UIImage *emojiImage = [UIImage imageNamed:imageName];
        NSAttributedString *imageString;
        if (emojiImage) {
            attach.image = emojiImage;
            attach.bounds = CGRectMake(0, -2, 15, 15);
            imageString = [NSAttributedString attributedStringWithAttachment:attach];
        }else{
            imageString = [[NSMutableAttributedString alloc]initWithString:imageName];
        }
        */
        
        NSAttributedString *imageString = [[NSMutableAttributedString alloc]initWithString:@""];
        
        //图片附件的文本长度是1
        //NSLog(@"emoj===%zd===size-w:%f==size-h:%f",imageString.length,imageString.size.width,imageString.size.height);
        NSUInteger length = attstr.length;
        NSRange newRange = NSMakeRange(result.range.location - lengthDetail, result.range.length);
        [attstr replaceCharactersInRange:newRange withAttributedString:imageString];
        
        lengthDetail += length - attstr.length;
    }
    
    NSString *newStr = [attstr string];
    
    //NSLog(@"del emoji\n原:%@\n新:%@\n富:%@\n长:%lu",originStr,newStr,attstr,(unsigned long)attstr.length);
    
    return newStr;
}


@end
